package com.fuhao.controller.member;
import com.alibaba.fastjson.JSONObject;
import com.fuhao.base.BaseWebController;
import com.fuhao.core.Constants.Constants;
import com.fuhao.core.base.BaseResponse;
import com.fuhao.dto.input.MemberInpDTO;
import com.fuhao.feign.MemberRegisterServiceFeign;
import com.fuhao.utils.RandomValidateCodeUtil;
import com.fuhao.utils.VoBeanUtils;
import com.fuhao.vo.RegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * 注册
 */
@Controller
@Slf4j
public class RegisterController extends BaseWebController {

    @Autowired
    private MemberRegisterServiceFeign memberRegisterServiceFeign;

	private static final String MB_REGISTER_FTL = "member/register";
    private static final String MB_LOGIN_FTL = "member/login";
	/**
	 * 跳转到注册页面
	 * 
	 * @return
	 */
	@GetMapping("/register")
	public String getRegister() {
		return MB_REGISTER_FTL;
	}

	/**
	 * 跳转到注册页面
	 * 
	 * @return
	 */
	@PostMapping("/register")
	public String postRegister(@ModelAttribute("registerVo") @Valid RegisterVo registerVo, BindingResult bindingResult, HttpSession httpSession, Model model) {
        // 1.参数验证
        if (bindingResult.hasErrors()) {
            // 获取第一个错误!
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            setErrorMsg(model, errorMsg);
            return MB_REGISTER_FTL;
        }
        //2.校验验证码
        Boolean isSuccess = RandomValidateCodeUtil.checkVerify(registerVo.getGraphicCode(), httpSession);
        if(!isSuccess){
            setErrorMsg(model,"图形验证码错误");
            return MB_REGISTER_FTL;
        }
        //3.注册
        // 将VO转换DTO
        MemberInpDTO voToDto = VoBeanUtils.voToDto(registerVo, MemberInpDTO.class);
        try {
            String registCode = registerVo.getRegistCode();
            BaseResponse<JSONObject> register = memberRegisterServiceFeign.register(voToDto, registCode);
            if (!register.getRtnCode().equals(Constants.HTTP_RES_CODE_200)) {
                model.addAttribute("error", register.getMsg());
                return MB_REGISTER_FTL;
            }
        } catch (Exception e) {
            log.error(">>>>>", e);
            model.addAttribute("error", "系统出现错误!");
            return MB_REGISTER_FTL;
        }

        // 注册成功,跳转到登陆页面
        return MB_LOGIN_FTL;
	}

}
